#include "static_file_request.h"

#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include "mmap_file.h"
#include "base/format_time.h"

namespace imserver {

bool StaticFileRequest::Response() {
  LOG_INFO("StaticFileRequest " << method_ << " " << url_ 
           << " addr=" << remote_addr());
  //TODO: 细化 压缩、Expire等Header
  int ttl = 86400;

  MMapFile * mmap_file = MMapFileCache::Instance().Get(file_path_.c_str());
  std::string content_type = "text/html";
  if (boost::algorithm::ends_with(url_, ".ico")) {
    content_type = "image/x-icon";
  }
  response_ = "HTTP/1.1 200 OK\r\nContent-Type: ";
  response_ += content_type;
  response_ += "; charset=utf-8\r\nConnection: close\r\nContent-Length: ";
  response_ += boost::lexical_cast<std::string>(mmap_file->size());
  response_ += "\r\nCache-Control: max-age=";
  response_ += boost::lexical_cast<std::string>(ttl);
  response_ += "\r\nExpires: ";
  response_ += base::GmtTime(time(NULL) + ttl);
  response_.append("\r\n\r\n");

  // TODO: 1) 减少memcpy
  try {
    response_.append(mmap_file->mapped_addr(), mmap_file->size());
  } catch (std::exception & e) {
    LOG_WARN("mmap_file string append err");
  }
  
  // TODO: OnSendComplete callback
  connection_->WriteResponse(response_);
  return true;
}

}

